package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@SpringBootApplication
public class DemoApplication {

    private static JdbcTemplate jdbcTemplate;


    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public static void main(String[] args) throws IOException {
        SpringApplication.run(DemoApplication.class, args);

        //生成UUID
        generateUUID("company");
        generateUUID("solution");

        //导出实体
        exportEntities("company", null);
        List<String> exceptColumns = new ArrayList<>();
        exceptColumns.add("company_id");
        exportEntities("solution", exceptColumns);

        //导出关系
        String sql2 = "select UUID() AS uuid,c.uuid AS startUuid,c.name AS startName,s.uuid AS endUuid,s.name AS endName from solution s,company c";
        exportRelations(sql2, "provide_solution", "solution", "company_provide_solution");

    }

    private static  void generateUUID(String tableName){
        String sql = "UPDATE "+ tableName+" SET uuid = UUID()";
        jdbcTemplate.update(sql);
    }

    /**
     * 功能描述 导出关系到json文件
     *
     * @param sql 查询关系的sql语句，结果集中的每条记录必须包含 uuid：关系的uuid，startUuid;
     *            关系起始实体的uuid，startName：关系起始实体的名称，endUuid：关系指向实体的uuid，endName：关系指向实体的名称 ,
     * @param relationLabel 关系的标签
     * @param endLabel 指向实体的标签（请用表名表示）
     * @param fileNameWithoutFileType 导出的json文件名（不带后缀名），请在名称中包含关联的表名，以防遗漏
     * @return void
     * @author lidashuai
     * @date 2019/1/18
     */
    private static void exportRelations(String sql, String relationLabel, String endLabel, String fileNameWithoutFileType) throws IOException {
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        JSONArray jsonArray = new JSONArray();
        for (Map<String, Object> map : list) {
            JSONObject nodeDetails = new JSONObject();
            nodeDetails.put("outRelations", new JSONArray());
            JSONArray inRelations = new JSONArray();
            JSONObject inRelation = new JSONObject();
            inRelation.put("startUuid", map.get("startUuid"));
            inRelation.put("startName", map.get("startName"));
            inRelation.put("label", relationLabel);
            JSONObject inRelationProperties = new JSONObject();
            inRelationProperties.put("uuid", map.get("uuid"));
            inRelation.put("properties", inRelationProperties);
            inRelations.add(inRelation);
            nodeDetails.put("inRelations", inRelations);
            JSONObject nodeProperties = new JSONObject();
            nodeProperties.put("uuid", map.get("endUuid"));
            nodeDetails.put("properties", nodeProperties);
            JSONArray labels = new JSONArray();
            labels.add(endLabel);
            nodeDetails.put("labels", labels);
            jsonArray.add(nodeDetails);
        }
        String json = JSON.toJSONString(jsonArray, true);
        Path rootLocation = Paths.get("export");//文件导出到export文件夹下
        if (Files.notExists(rootLocation)) {
            Files.createDirectories(rootLocation);
        }
        Path path = rootLocation.resolve(fileNameWithoutFileType + ".json");//以表名作为文件名
        byte[] strToBytes = json.getBytes("UTF-8");
        Files.write(path, strToBytes);
    }

    /**
     * 导出实体
     * @param tableName     表名
     * @param exceptColumns 需要排除的字段（id默认排除）
     * @return void
     * @author lidashuai
     * @date 2019/1/18
     */
    private static void exportEntities(String tableName, List<String> exceptColumns) throws IOException {
        JSONArray jsonArray = new JSONArray();
        String sql2 = "select * from " + tableName;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql2);
        for (Map<String, Object> map : list) {
            JSONObject nodeDetails = new JSONObject();
            nodeDetails.put("outRelations", new JSONArray());
            nodeDetails.put("inRelations", new JSONArray());
            map.remove("id");//去掉id字段
            if (exceptColumns != null) {
                for (String column : exceptColumns) {
                    map.remove(column);
                }
            }
            JSONObject properties = new JSONObject(map);
            nodeDetails.put("properties", properties);
            JSONArray labels = new JSONArray();
            labels.add(tableName);//以表名作为实体标签
            nodeDetails.put("labels", labels);
            jsonArray.add(nodeDetails);
        }
        String json = JSON.toJSONString(jsonArray, true);
        //文件目录
        Path rootLocation = Paths.get("export");//文件导出到export文件夹下
        if (Files.notExists(rootLocation)) {
            Files.createDirectories(rootLocation);
        }
        Path path = rootLocation.resolve(tableName + ".json");//以表名作为文件名
        byte[] strToBytes = json.getBytes("UTF-8");
        Files.write(path, strToBytes);
    }
}

